<template>
  <div class="sku-page">
    <div class="page-header">
      <h2>
        <el-icon><Grid /></el-icon>
        商品SKU管理
      </h2>
      <el-button type="primary" @click="handleCreateSKU">
        <el-icon><Plus /></el-icon>
        生成SKU
      </el-button>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：商品列表 -->
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>商品列表</span>
          </template>
          <el-input
            v-model="searchText"
            placeholder="搜索商品..."
            clearable
            style="margin-bottom: 15px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-menu
            :default-active="selectedProductId"
            @select="handleSelectProduct"
          >
            <el-menu-item
              v-for="product in filteredProducts"
              :key="product.id"
              :index="product.id.toString()"
            >
              <div class="product-menu-item">
                <div>
                  <div>{{ product.name }}</div>
                  <div class="product-code">{{ product.code }}</div>
                </div>
                <el-tag size="small" type="info">
                  {{ product.skuCount || 0 }} SKU
                </el-tag>
              </div>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>

      <!-- 右侧：SKU列表 -->
      <el-col :span="16">
        <el-card v-if="selectedProduct">
          <template #header>
            <div class="card-header">
              <span>{{ selectedProduct.name }} - SKU列表</span>
              <el-button type="primary" size="small" @click="handleBatchEdit">
                批量编辑
              </el-button>
            </div>
          </template>

          <el-table :data="skuList" stripe>
            <el-table-column type="selection" width="55" />
            <el-table-column prop="skuCode" label="SKU编码" width="150" />
            <el-table-column label="规格" min-width="200">
              <template #default="{ row }">
                <div class="spec-tags">
                  <el-tag
                    v-for="(value, key) in row.specifications"
                    :key="key"
                    size="small"
                  >
                    {{ key }}:{{ value }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" width="100">
              <template #default="{ row }">
                ¥{{ row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="100">
              <template #default="{ row }">
                <el-tag :type="row.stock > 10 ? 'success' : 'warning'">
                  {{ row.stock }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-switch
                  v-model="row.status"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" text @click="handleEditSKU(row)">
                  编辑
                </el-button>
                <el-button type="danger" size="small" text @click="handleDeleteSKU(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-empty v-else description="请在左侧选择商品" />
      </el-col>
    </el-row>

    <!-- 生成SKU对话框 -->
    <el-dialog v-model="skuDialogVisible" title="生成SKU" width="800px">
      <el-steps :active="currentStep" finish-status="success" align-center>
        <el-step title="选择商品" />
        <el-step title="配置属性" />
        <el-step title="生成SKU" />
      </el-steps>

      <!-- 步骤1：选择商品 -->
      <div v-show="currentStep === 0" class="step-content">
        <el-form label-width="100px">
          <el-form-item label="选择商品">
            <el-select v-model="skuForm.productId" placeholder="请选择商品" style="width: 100%" filterable>
              <el-option
                v-for="product in products"
                :key="product.id"
                :label="`${product.code} - ${product.name}`"
                :value="product.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤2：配置属性 -->
      <div v-show="currentStep === 1" class="step-content">
        <div
          v-for="(attr, index) in skuForm.attributes"
          :key="index"
          class="attribute-config"
        >
          <div class="attr-header">
            <h4>属性 {{ index + 1 }}</h4>
            <el-button type="danger" size="small" text @click="handleRemoveAttribute(index)">
              删除
            </el-button>
          </div>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="属性名称">
                <el-input v-model="attr.name" placeholder="如：颜色、尺码" />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="属性值">
                <el-tag
                  v-for="(value, vIndex) in attr.values"
                  :key="vIndex"
                  closable
                  @close="handleRemoveValue(index, vIndex)"
                  style="margin-right: 10px"
                >
                  {{ value }}
                </el-tag>
                <el-input
                  v-model="attr.newValue"
                  placeholder="输入后回车添加"
                  style="width: 200px"
                  @keyup.enter="handleAddValue(index)"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-button type="primary" plain @click="handleAddAttribute">
          <el-icon><Plus /></el-icon>
          添加属性
        </el-button>

        <el-divider />

        <el-alert
          v-if="skuCombinationCount > 0"
          :title="`将生成 ${skuCombinationCount} 个SKU`"
          type="info"
          :closable="false"
        />
      </div>

      <!-- 步骤3：生成SKU -->
      <div v-show="currentStep === 2" class="step-content">
        <el-table :data="generatedSKUs" stripe max-height="400">
          <el-table-column prop="skuCode" label="SKU编码" width="150" />
          <el-table-column label="规格组合" min-width="200">
            <template #default="{ row }">
              <el-tag
                v-for="(value, key) in row.specifications"
                :key="key"
                size="small"
                style="margin-right: 5px"
              >
                {{ key}}:{{ value }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="价格" width="150">
            <template #default="{ row }">
              <el-input-number
                v-model="row.price"
                :min="0"
                :precision="2"
                size="small"
                style="width: 120px"
              />
            </template>
          </el-table-column>
          <el-table-column label="库存" width="120">
            <template #default="{ row }">
              <el-input-number
                v-model="row.stock"
                :min="0"
                size="small"
                style="width: 100px"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <el-button @click="skuDialogVisible = false">取消</el-button>
        <el-button v-if="currentStep > 0" @click="currentStep--">上一步</el-button>
        <el-button v-if="currentStep < 2" type="primary" @click="handleNextStep">下一步</el-button>
        <el-button v-if="currentStep === 2" type="primary" @click="handleSubmitSKU">确认生成</el-button>
      </template>
    </el-dialog>

    <!-- 编辑SKU对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑SKU" width="600px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="SKU编码">
          <el-input v-model="editForm.skuCode" disabled />
        </el-form-item>

        <el-form-item label="规格">
          <div class="spec-tags">
            <el-tag
              v-for="(value, key) in editForm.specifications"
              :key="key"
            >
              {{ key }}:{{ value }}
            </el-tag>
          </div>
        </el-form-item>

        <el-form-item label="价格">
          <el-input-number v-model="editForm.price" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>

        <el-form-item label="库存">
          <el-input-number v-model="editForm.stock" :min="0" style="width: 100%" />
        </el-form-item>

        <el-form-item label="成本价">
          <el-input-number v-model="editForm.costPrice" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>

        <el-form-item label="条形码">
          <el-input v-model="editForm.barcode" />
        </el-form-item>

        <el-form-item label="状态">
          <el-switch
            v-model="editForm.status"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitEdit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Grid, Plus, Search } from '@element-plus/icons-vue'

const searchText = ref('')
const skuDialogVisible = ref(false)
const editDialogVisible = ref(false)
const currentStep = ref(0)
const selectedProductId = ref('')
const selectedProduct = ref(null)

const products = ref([
  { id: 1, code: 'P001', name: 'T恤', skuCount: 12 },
  { id: 2, code: 'P002', name: '运动鞋', skuCount: 20 }
])

const skuData = ref([
  {
    productId: 1,
    skuCode: 'P001-BLK-S',
    specifications: { 颜色: '黑色', 尺码: 'S' },
    price: 99,
    stock: 50,
    status: true
  },
  {
    productId: 1,
    skuCode: 'P001-BLK-M',
    specifications: { 颜色: '黑色', 尺码: 'M' },
    price: 99,
    stock: 80,
    status: true
  },
  {
    productId: 1,
    skuCode: 'P001-WHT-S',
    specifications: { 颜色: '白色', 尺码: 'S' },
    price: 99,
    stock: 30,
    status: true
  }
])

const skuForm = reactive({
  productId: null,
  attributes: [
    { name: '', values: [], newValue: '' }
  ]
})

const editForm = reactive({
  skuCode: '',
  specifications: {},
  price: 0,
  stock: 0,
  costPrice: 0,
  barcode: '',
  status: true
})

const generatedSKUs = ref([])

const filteredProducts = computed(() => {
  if (!searchText.value) return products.value
  return products.value.filter(p =>
    p.name.includes(searchText.value) ||
    p.code.includes(searchText.value)
  )
})

const skuList = computed(() => {
  if (!selectedProduct.value) return []
  return skuData.value.filter(sku => sku.productId === selectedProduct.value.id)
})

const skuCombinationCount = computed(() => {
  const validAttrs = skuForm.attributes.filter(attr => attr.name && attr.values.length > 0)
  if (validAttrs.length === 0) return 0
  return validAttrs.reduce((count, attr) => count * attr.values.length, 1)
})

const handleSelectProduct = (index) => {
  const product = products.value.find(p => p.id.toString() === index)
  if (product) {
    selectedProduct.value = product
    selectedProductId.value = index
  }
}

const handleCreateSKU = () => {
  skuForm.productId = null
  skuForm.attributes = [{ name: '', values: [], newValue: '' }]
  currentStep.value = 0
  skuDialogVisible.value = true
}

const handleAddAttribute = () => {
  skuForm.attributes.push({ name: '', values: [], newValue: '' })
}

const handleRemoveAttribute = (index) => {
  skuForm.attributes.splice(index, 1)
}

const handleAddValue = (index) => {
  const attr = skuForm.attributes[index]
  if (attr.newValue.trim()) {
    attr.values.push(attr.newValue.trim())
    attr.newValue = ''
  }
}

const handleRemoveValue = (attrIndex, valueIndex) => {
  skuForm.attributes[attrIndex].values.splice(valueIndex, 1)
}

const handleNextStep = () => {
  if (currentStep.value === 0 && !skuForm.productId) {
    ElMessage.warning('请选择商品')
    return
  }
  if (currentStep.value === 1) {
    generateSKUs()
  }
  currentStep.value++
}

const generateSKUs = () => {
  const validAttrs = skuForm.attributes.filter(attr => attr.name && attr.values.length > 0)
  
  if (validAttrs.length === 0) {
    ElMessage.warning('请至少配置一个属性')
    return
  }

  // 生成笛卡尔积
  const combinations = cartesianProduct(validAttrs.map(attr => 
    attr.values.map(value => ({ name: attr.name, value }))
  ))

  generatedSKUs.value = combinations.map((combo, index) => {
    const specs = {}
    let skuCode = `P${skuForm.productId}-`
    
    combo.forEach((item, i) => {
      specs[item.name] = item.value
      skuCode += item.value.substring(0, 3).toUpperCase()
      if (i < combo.length - 1) skuCode += '-'
    })

    return {
      skuCode,
      specifications: specs,
      price: 0,
      stock: 0
    }
  })
}

const cartesianProduct = (arrays) => {
  return arrays.reduce((acc, array) => {
    return acc.flatMap(x => array.map(y => [...x, y]))
  }, [[]])
}

const handleEditSKU = (row) => {
  Object.assign(editForm, { ...row })
  editDialogVisible.value = true
}

const handleDeleteSKU = (row) => {
  ElMessage.success('删除成功')
}

const handleBatchEdit = () => {
  ElMessage.info('批量编辑功能开发中')
}

const handleSubmitSKU = () => {
  ElMessage.success(`成功生成 ${generatedSKUs.value.length} 个SKU`)
  skuDialogVisible.value = false
}

const handleSubmitEdit = () => {
  ElMessage.success('修改成功')
  editDialogVisible.value = false
}
</script>

<style scoped>
.sku-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
}

.page-header h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.product-code {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.spec-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.step-content {
  padding: 30px 20px;
  min-height: 300px;
}

.attribute-config {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.attr-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.attr-header h4 {
  margin: 0;
}
</style>

